const path = require('path');

const express = require('express');

const config = require('../config')

const parseConf = require('./parse.conf');
const ParseServer = require('parse-server').ParseServer;

const port = parseConf.port;
const apiPath = parseConf.apiPath;
const serverURL = parseConf.serverURL;

const api = new ParseServer({
  databaseURI: 'mongodb://localhost:27017/parse',
  // cloud: path.resolve(__dirname, './cloud/main.js'),
  appId: parseConf.appId,
  masterKey: parseConf.masterKey,

  javascriptKey: parseConf.javascriptKey,
  // fileKey: parseConf.fileKey,
  // push: {}, // See the Push wiki page
  // filesAdapter: ...,

  mountPath: `/${apiPath}`,
  port: port,
  serverURL: serverURL
});

const ParseDashboard = require('parse-dashboard');

const dashboard = new ParseDashboard({
  "apps": [
    {
      "serverURL": serverURL,
      "appId": parseConf.appId,
      "masterKey": parseConf.masterKey,
      "appName": "MyLocalDevApp"
    }
  ]
});

const setup = {
  server: api,
  connectExpress (app) {
    // Serve the Parse API at /parse URL prefix
    app.use(`/${apiPath}`, api);
  },
  buildExpress () {
    const app = express();
    this.connectExpress(app);

    app.get('/', function(req, res) {
      res.status(200).send('I dream of being a website.  Please star the parse-server repo on GitHub!');
    });

    app.use('/dashboard', dashboard);

    app.listen(port, function (err) {
      if (err) {
        console.log('[err], parse server start failed', err);
        return
      }
      console.log('parse server started');
    })
  }
};

module.exports = setup;

// test script
// const app = express();
// setup.connectExpress(app);

// app.get('/', function(req, res) {
//   res.status(200).send('I dream of being a website.  Please star the parse-server repo on GitHub!');
// });

// app.listen(port, function (err) {
//   if (err) {
//     console.log('[err], parse server start failed', err);
//     return
//   }
//   console.log('parse server started');
// })
